const express = require('express')
const axois = require('axios')

/**
 * APIUrl：http://lbsyun.baidu.com/index.php?title=webapi
 */

// BMap AK
const ak = 'WO1wkmjyhZI7uR15mcmABTCrOYKba5Pe'

const request = axois.create({
  baseURL: 'http://api.map.baidu.com/',
  timeout: 3000
})

request.interceptors.request.use(config => {
  if (config.method === 'get') {
    config.params = {
      ak,
      output: 'json',
      ...config.params
    }
  }
  return config
}, err => {
  return Promise.reject(err)
})

const router = express.Router()

/**
 * http://api.map.baidu.com/place/v2/search?query=ATM机&tag=银行&region=北京&output=json&ak=您的ak //GET请求
 */
router.get('/search', async (req, res) => {
  const {
    data
  } = await request.get('place/v2/search', {
    params: req.query
  })
  res.json(data)
})

/**
 * http://api.map.baidu.com/place/v2/suggestion?query=天安门&region=北京&city_limit=true&output=json&ak=你的ak //GET请求
 */
router.get('/suggestion', async (req, res) => {
  const {
    data
  } = await request.get('place/v2/suggestion', {
    params: req.query
  })
  res.json(data)
})

/**
 * http://api.map.baidu.com/geocoder/v2/?address=北京市海淀区上地十街10号&output=json&ak=您的ak //GET请求
 */
router.get('/geocoder', async (req, res) => {
  const {
    data
  } = await request.get('geocoder/v2/', {
    params: req.query
  })
  res.json(data)
})

/**
 * http://api.map.baidu.com/location/ip?ip=xx.xx.xx.xx&ak=您的AK&coor=bd09ll
 */
router.get('/location', async (req, res) => {
  const {
    data
  } = await request.get('location/ip', {
    params: req.query
  })
  res.json(data)
})

module.exports = router
